﻿using System;
using System.Web;
using Microsoft.Practices.Unity;

namespace WebProject
{
    public class RequestLifeTimeManager : LifetimeManager, IDisposable
    {
        private readonly Guid m_Id = Guid.NewGuid();

        public override object GetValue()
        {
            if (HttpContext.Current == null)
            {
                return null;
            }
            lock (HttpContext.Current.Items)
            {
                return HttpContext.Current.Items[m_Id];
            }
        }

        public override void RemoveValue()
        {
            if (HttpContext.Current == null)
            {
                return;
            }
            lock (HttpContext.Current.Items)
            {
                HttpContext.Current.Items.Remove(m_Id);
            }
        }

        public override void SetValue(object newValue)
        {
            if (HttpContext.Current == null)
            {
                return;
            }
            lock (HttpContext.Current.Items)
            {
                HttpContext.Current.Items[m_Id] = newValue;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            RemoveValue();
        }

        ~RequestLifeTimeManager()
        {
            Dispose(false);
        }
    }
}